export function dateFormat(dateString,fmt) {
    let date = new Date(dateString);
		let ret;
		const opt = {
			"Y+": date.getFullYear().toString(), // 年
			"m+": (date.getMonth() + 1).toString(), // 月
			"d+": date.getDate().toString(), // 日
			"H+": date.getHours().toString(), // 时
			"M+": date.getMinutes().toString(), // 分
			"S+": date.getSeconds().toString() // 秒
			// 有其他格式化字符需求可以继续添加，必须转化成字符串
		};
		for (let k in opt) {
			ret = new RegExp("(" + k + ")").exec(fmt);
			if (ret) {
				fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
			};
		};
		return fmt;
}

export function timeFix () {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome () {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 LOL', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent () {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader (callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE () {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate (id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

/* 生成随机uuid
*	n：uuid的长度
* type：类型（0-大小写字母+数字，1-小写字母+数字，2-纯数字，3-大小写字母，4-小写字母）
*/
export function uuid(n=6,type=0){
	let res='', uType=0;
	const __uuidLetter = function(){
		const __tempArr = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
		return __tempArr[Math.floor(Math.random()*26)];
	}
	for (let i=0;i<n;i++) {
		switch(type) {
			case 1:
				uType = Math.floor(Math.random()*2);
				if (uType===0) {
					res += Math.floor(Math.random()*10).toString()
				} else {
					res += __uuidLetter()
				}
				break;
			case 2:
				res += Math.floor(Math.random()*10).toString()
				break;
			case 3:
				uType = Math.floor(Math.random()*2);
				if (uType===0) {
					res += __uuidLetter()
				} else {
					res += __uuidLetter().toUpperCase()
				}
				break;
			case 4:
				res += __uuidLetter()
				break;
			default:
				uType = Math.floor(Math.random()*3);
				if (uType===0) {
					res += Math.floor(Math.random()*10).toString()
				} else if (uType===1) {
					res += __uuidLetter()
				} else {
					res += __uuidLetter().toUpperCase()
				}
				break;
		}
	}
	return res;
}

/**
 * 检验上传文件是否合格
 * @param fileInfo
 * @param maxSize
 * @param typeArr
 */
export function checkFile(fileInfo, maxSize, typeArr) {
  if (fileInfo.size >= maxSize) {
    fileInfo.status = 'error'
    return {
      success: false,
      msg: "文件大小超过最大限度"
    }
  }
  if (fileInfo.size <= 0) {
    fileInfo.status = 'error'
    return {
      success: false,
      msg: "所选信息中存在空文件或目录"
    }
  }
  const type = fileInfo.name.slice(fileInfo.name.lastIndexOf('.') + 1).toLowerCase()
  if (!typeArr.includes('.' + type)) {
    fileInfo.status = 'error'
    return {
      success: false,
      msg: "不支持以 ."+ type + "扩展类型的文件或图片上传!"
    }
  }
  return {
    success: true,
    msg: "上传成功!"
  }
}

export function parseDemandText() {
  let text = "1.支持Excel2007及以上版本文件。\n";
  text += "2.为保证数据顺利导入，请下载\""+ "<a-button onclick=\"downloadFile()\" " +
    "style=\"width: 100%;text-align: center;color:#FA541C;cursor:pointer;\">导入模板</a-button>\"\n";
  text += "3.导入新增数据时不能超过5000行。\n";
  text += "4.导入更新数据时不能超过2000行。";
  return text;
}

/**
 * 根据列集合信息生成文本描述
 * @param columnInfos
 */
export function parseExcelFieldText(columnInfos) {
  let text = "", typeName = {
    "System.String": "文本。如: 钟孝本",
    "System.Int32": "数字。如: 4377",
    "System.Int64": "数字。如: 4377",
    "System.Decimal": "数字。如: 43.77",
    "System.DateTimeOffset": "日期。 如: 2023/3/1",
    "System.DateTime": "日期。 如: 2023/3/1",
  };

  columnInfos.forEach(x => {
    text += x.columnComment + "(" + (x.isRequired ? "必填" : "非必填")  + "): ";
    text += (typeName[x.dataType] ? typeName[x.dataType] : ("文本。 可选项为: " + x.remark)) + "\n" ;
  });

  return text;
}

export function downloadFile(res) {
  let blob = new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' })
  let contentDisposition = res.headers['content-disposition']
  let pattern = new RegExp('filename=([^;]+\\.[^\.;]+);*')
  let result = pattern.exec(contentDisposition)
  let filename = result[1];
  let downloadElement = document.createElement('a')
  let href = window.URL.createObjectURL(blob) // 创建下载的链接
  let reg = /^["](.*)["]$/g
  downloadElement.style.display = 'none'
  downloadElement.href = href
  downloadElement.download = decodeURI(filename.replace(reg, '$1')) // 下载后文件名
  document.body.appendChild(downloadElement)
  downloadElement.click() // 点击下载
  document.body.removeChild(downloadElement) // 下载完成移除元素
  window.URL.revokeObjectURL(href)
}

export function getObjectType(obj){
	if (typeof obj !== 'object') {
		return null;
	} else {
		let objTypeStr = Object.prototype.toString.call(obj).toLowerCase().trim();
		objTypeStr = objTypeStr.substr(1,objTypeStr.length-2)
		let tempA = objTypeStr.split(" ");
		return tempA[1];
	}	
}

export function getUserDefaultArea($store,arr,valueField='code'){
  let res = ''
  const _default = $store.getters['userInfo']['workShopType']
  for (let i=0;i<arr.length;i++){
    if (String(arr[i][valueField])===Sring(_default)) {
      res = _default
      break;
    }
  }
  return res
}

export function getUserDefaultLine($store,arr,valueField='productionlineId'){
  let res = ''
  const _default = $store.getters['userInfo']['productionlineId']
  for (let i=0;i<arr.length;i++){
    if (arr[i][valueField]===_default) {
      res = _default
      break;
    }
  }
	return res
}
